/**
 * 文件下载管理器类
 * 基于Layui框架的文件下载功能封装
 * 
 * @author Your Name
 * @version 1.0.0
 */
class FileDownloadManager {
    /**
     * 构造函数
     * @param {Object} options 配置选项
     */
    constructor(options = {}) {
        this.layui = layui;
        this.layer = layui.layer;
        this.form = layui.form;
        this.element = layui.element;
        
        // 默认配置
        this.config = {
            time: '',
            event: '',
            srcIp: '',
            srcPath: '',
            srcUsername: '',
            srcPassword: '',
            destIp: '',
            destPath: '',
            destUsername: '',
            destPassword: '',
            transferMode: 'scp', // scp 或 server
            ...options
        };
        
        // 事件回调
        this.callbacks = {
            onDownloadStart: null,
            onDownloadProgress: null,
            onDownloadComplete: null,
            onDownloadError: null,
            ...options.callbacks
        };

        // 传输状态管理 - 新增
        this.isTransferring = false;
        this.currentTransfer = {
            fileName: '',
            totalSize: 0,
            transferredSize: 0,
            speed: 0,
            remainingTime: 0,
            progress: 0,
            startTime: null,
            progressTimer: null
        };
        
        this.init();
    }
    
    /**
     * 初始化
     */
    init() {
        if (window.SocketClient && window.SocketClient.socket) {

            //=========== socket监听事件 =========
            // 监听下载进度更新
            window.SocketClient.socket.on('download_recall', function(data) {
                console.log('下载召回:', data);
            });
            // 监听传输终止事件
            window.SocketClient.socket.on('transfer_stopped', function(data) {
                console.log('传输停止:', data);
            });
            // 监听下载进度更新
            window.SocketClient.socket.on('progress_list', (data) => {
                console.log('下载进度更新:', data);
                
                var progress_num = data[0].percent
                var progress = data[0].percent_str
                var speed = data[0].speed_str
                var remainingTime = data[0].eta_str
                var transferredSize = data[0].sent_str
                var totalSize = data[0].size_str
                this.updateProgressDisplay(progress_num,progress, speed, remainingTime, transferredSize, totalSize);
            });

        }
        console.log('FileDownloadManager 初始化完成');
    }
    
    /**
     * 生成下载表单HTML
     * @returns {string} HTML字符串
     */
    generateFormHTML() {
        return `
            <form class="layui-form download-form" lay-filter="downloadForm">
                <!-- 传输模式选择 -->
                <div class="layui-form-item">
                    <label class="layui-form-label">传输模式</label>
                    <div class="layui-input-block transfer-mode-group">
                        <input type="radio" name="transferMode" lay-filter="transferMode" value="scp" title="scp直传" 
                               ${this.config.transferMode === 'scp' ? 'checked' : ''}>
                        <input type="radio" name="transferMode" lay-filter="transferMode" value="server" title="服务器中转" 
                               ${this.config.transferMode === 'server' ? 'checked' : ''}>
                    </div>
                </div>
                
                <!-- 源主机IP -->
                <div class="layui-form-item">
                    <label class="layui-form-label">源主机IP</label>
                    <div class="layui-input-block">
                        <input type="text" name="srcIp" placeholder="请输入源主机IP地址" 
                               autocomplete="off" class="layui-input" value="${this.config.srcIp}"
                               lay-verify="required|ip">
                    </div>
                </div>
                
                <!-- 源文件路径 -->
                <div class="layui-form-item">
                    <label class="layui-form-label">源文件路径</label>
                    <div class="layui-input-block">
                        <input type="text" name="srcPath" placeholder="请输入源文件完整路径" 
                               autocomplete="off" class="layui-input" value="${this.config.srcPath}"
                               lay-verify="required">
                    </div>
                </div>
                
                <!-- 目标主机IP -->
                <div class="layui-form-item">
                    <label class="layui-form-label">目标主机IP</label>
                    <div class="layui-input-block">
                        <input type="text" name="destIp" placeholder="请输入目标主机IP地址" 
                               autocomplete="off" class="layui-input" value="${this.config.destIp}"
                               lay-verify="required|ip">
                    </div>
                </div>
                
                <!-- 目标接收路径 -->
                <div class="layui-form-item">
                    <label class="layui-form-label">目标接收路径</label>
                    <div class="layui-input-block">
                        <div class="path-input-group">
                            <input type="text" name="destPath" placeholder="请输入或选择目标文件接收路径" 
                                   autocomplete="off" class="layui-input" value="${this.config.destPath}"
                                   lay-verify="required">
                            <button type="button" class="layui-btn layui-btn-primary path-select-btn" 
                                    id="selectPathBtn">
                                <i class="layui-icon layui-icon-folder"></i>
                                选择路径
                            </button>
                        </div>
                    </div>
                </div>
                
                <!-- 操作按钮 -->
                <div class="layui-form-item button-group">
                    <button type="button" class="layui-btn layui-btn-lg" lay-submit lay-filter="startDownload">
                        <i class="layui-icon layui-icon-download-circle"></i>
                        开始下载
                    </button>
                    <button type="button" class="layui-btn layui-btn-normal layui-btn-lg" id="showProgressBtn">
                        <i class="layui-icon layui-icon-chart"></i>
                        传输进度
                    </button>
                    <button type="button" class="layui-btn layui-btn-primary layui-btn-lg" id="cancelDownload">
                        <i class="layui-icon layui-icon-close"></i>
                        取消
                    </button>
                </div>
            </form>
        `;
    }
    
    /**
     * 显示下载配置对话框
     * @param {Object} options 配置选项
     * @returns {number} 弹层索引
     */
    showDownloadDialog(options = {}) {
        // 更新配置
        Object.assign(this.config, options);
        
        const content = this.generateFormHTML();
        
        const index = this.layer.open({
            type: 1,
            title: [
                '<i class="layui-icon layui-icon-set" style="margin-right: 10px;"></i>文件下载设置', 
                'font-size: 18px; font-weight: 500;'
            ],
            area: ['600px', 'auto'],
            maxmin: true,
            content: content,
            success: (layero, index) => {
                this.setupFormEvents(layero, index);
                this.form.render(); // 重新渲染表单
                this.setupCustomValidation(); // 设置自定义验证
            }
        });
        
        return index;
    }
    
    /**
     * 设置表单事件
     * @param {jQuery} layero 弹层jQuery对象
     * @param {number} layerIndex 弹层索引
     */
    setupFormEvents(layero, layerIndex) {
        // 路径选择按钮事件
        layero.find('#selectPathBtn').on('click', () => {
            this.showPathSelector(layero);
        });

         // 传输进度按钮事件 
        layero.find('#showProgressBtn').on('click', () => {
            this.layer.close(layerIndex);
            this.showTransferProgress();
            // 向后端发送获取传输进度的请求
            window.SocketClient.socket.emit('get_progress', {});
        });
        
        // 取消按钮事件
        layero.find('#cancelDownload').on('click', () => {
            this.layer.close(layerIndex);
        });
        
        // 表单提交事件
        this.form.on('submit(startDownload)', (data) => {
            this.handleDownload(data.field, layerIndex);
            return false;
        });


        // layero.find('#transferList').on('click', () => {
        //     this.handleTransferList(layerIndex);
        // });

        // layero.find('#stopTransfer').on('click', () => {
        //     this.handleStopTransfer(layerIndex);
        // });

        
        // 传输模式切换事件
        this.form.on('radio(transferMode)', (data) => {
            console.log('传输模式切换为:', data.value);
            this.config.transferMode = data.value;
            this.onTransferModeChange(data.value);
        });
        
        // // 实时保存表单数据
        // layero.find('input').on('input', (e) => {
        //     const name = $(e.target).attr('name');
        //     const value = $(e.target).val();
        //     if (name && this.config.hasOwnProperty(name)) {
        //         this.config[name] = value;
        //     }
        // });
    }
    
    /**
     * 设置自定义验证规则
     */
    setupCustomValidation() {
        // IP地址验证
        this.form.verify({
            ip: function(value) {
                const ipRegex = /^(\d{1,3}\.){3}\d{1,3}$/;
                if (!ipRegex.test(value)) {
                    return 'IP地址格式不正确';
                }
                const parts = value.split('.');
                for (let part of parts) {
                    if (parseInt(part) > 255) {
                        return 'IP地址格式不正确';
                    }
                }
            }
        });
    }
    
    /**
     * 传输模式变化处理
     * @param {string} mode 传输模式
     */
    onTransferModeChange(mode) {
        // 可以根据不同模式调整UI或配置
        if (mode === 'server') {
            this.layer.msg('已切换到服务器中转模式', {icon: 1, time: 1000});
        } else {
            this.layer.msg('已切换到scp直传模式', {icon: 1, time: 1000});
        }
    }
    
    /**
     * 显示路径选择器
     * @param {jQuery} parentLayero 父弹层
     */
    showPathSelector(parentLayero) {
        const commonPaths = this.getCommonPaths();
        
        let pathOptions = '';
        commonPaths.forEach((pathInfo, index) => {
            pathOptions += `
                <div class="path-option" data-path="${pathInfo.path}" data-index="${index}">
                    <i class="layui-icon ${pathInfo.icon}" style="margin-right: 8px; color: #666;"></i>
                    <span style="font-weight: 500;">${pathInfo.name}</span>
                    <br>
                    <small style="color: #999; margin-left: 24px;">${pathInfo.path}</small>
                </div>
            `;
        });
        
        const pathSelectorHTML = `
            <div style="padding: 20px;">
                <div style="margin-bottom: 15px;">
                    <label class="layui-form-label" style="width: auto; padding: 0; margin-right: 10px;">自定义路径:</label>
                    <input type="text" placeholder="或直接输入路径" class="layui-input" id="customPathInput"
                           style="display: inline-block; width: calc(100% - 100px);">
                </div>
                <div style="margin-bottom: 15px;">
                    <label style="font-weight: 500; color: #333;">常用路径:</label>
                </div>
                <div class="path-selector">
                    ${pathOptions}
                </div>
                <div style="text-align: center; margin-top: 20px;">
                    <button type="button" class="layui-btn" id="confirmPathBtn">
                        <i class="layui-icon layui-icon-ok"></i>
                        确定选择
                    </button>
                    <button type="button" class="layui-btn layui-btn-primary" id="cancelPathBtn">
                        <i class="layui-icon layui-icon-close"></i>
                        取消
                    </button>
                </div>
            </div>
        `;
        
        const pathIndex = this.layer.open({
            type: 1,
            title: [
                '<i class="layui-icon layui-icon-folder" style="margin-right: 10px;"></i>选择保存路径',
                'font-size: 16px;'
            ],
            area: ['480px', '420px'],
            content: pathSelectorHTML,
            success: (pathLayero, pathLayerIndex) => {
                this.setupPathSelectorEvents(pathLayero, pathLayerIndex, parentLayero);
            }
        });
    }
    
    /**
     * 设置路径选择器事件
     */
    setupPathSelectorEvents(pathLayero, pathLayerIndex, parentLayero) {
        let selectedPath = '';
        
        // 路径选项点击事件
        pathLayero.find('.path-option').on('click', function() {
            selectedPath = $(this).data('path');
            pathLayero.find('#customPathInput').val(selectedPath);
            pathLayero.find('.path-option').removeClass('selected');
            $(this).addClass('selected');
        });
        
        // 自定义路径输入事件
        pathLayero.find('#customPathInput').on('input', function() {
            selectedPath = $(this).val();
            pathLayero.find('.path-option').removeClass('selected');
        });
        
        // 确定按钮事件
        pathLayero.find('#confirmPathBtn').on('click', () => {
            if (selectedPath.trim()) {
                parentLayero.find('input[name="destPath"]').val(selectedPath);
                this.config.destPath = selectedPath;
                this.layer.close(pathLayerIndex);
                this.layer.msg('路径选择成功', {icon: 1, time: 1000});
            } else {
                this.layer.msg('请选择或输入路径', {icon: 2});
            }
        });
        
        // 取消按钮事件
        pathLayero.find('#cancelPathBtn').on('click', () => {
            this.layer.close(pathLayerIndex);
        });
    }
    
    /**
     * 获取常用路径列表
     * @returns {Array} 路径信息数组
     */
    getCommonPaths() {
        return [
            {
                name: 'Downloads',
                path: '/home/user/Downloads',
                icon: 'layui-icon-download-circle'
            },
            {
                name: 'Documents',
                path: '/home/user/Documents',
                icon: 'layui-icon-file'
            },
            {
                name: 'Temporary',
                path: '/tmp',
                icon: 'layui-icon-template-1'
            },
            {
                name: 'Windows Downloads',
                path: 'C:\\Users\\用户\\Downloads',
                icon: 'layui-icon-windows'
            },
            {
                name: 'Windows Desktop',
                path: 'C:\\Users\\用户\\Desktop',
                icon: 'layui-icon-desktop'
            },
            {
                name: 'Custom Folder',
                path: '/var/data/downloads',
                icon: 'layui-icon-folder'
            }
        ];
    }

    /**
    * 显示传输进度弹窗
    * @returns {number} 弹层索引
    */
    showTransferProgress() {
        // // 检查是否有正在进行的传输
        // if (!this.isTransferring) {
        //     this.layer.msg('当前没有进行中的传输任务', {icon: 6});
        //     return;
        // }
        
        const progressHTML = `
            <div style="padding: 25px;">
                <!-- 传输信息 -->
                <div style="margin-bottom: 20px; padding: 15px; background: #f8f9fa; border-radius: 6px;">
                    <div style="margin-bottom: 8px;">
                        <strong>文件：</strong><span id="transferFileName">${this.currentTransfer.fileName || '未知文件'}</span>
                    </div>
                    <div style="margin-bottom: 8px;">
                        <strong>模式：</strong><span id="transferMode">${this.config.transferMode === 'scp' ? 'SCP直传' : '服务器中转'}</span>
                    </div>
                    <div>
                        <strong>状态：</strong><span id="transferStatus" style="color: #52c41a;">传输中</span>
                    </div>
                </div>
                
                <!-- 进度条 -->
                <div style="margin-bottom: 20px;">
                    <div style="display: flex; justify-content: space-between; margin-bottom: 8px;">
                        <span>传输进度</span>
                        <span id="progressPercent">0%</span>
                    </div>
                    <div class="layui-progress layui-progress-big" lay-filter="transferProgress">
                        <div class="layui-progress-bar layui-bg-blue" lay-percent="0%"></div>
                    </div>
                </div>
                
                <!-- 传输统计 -->
                <div style="display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 15px; margin-bottom: 25px;">
                    <div style="text-align: center; padding: 10px; background: #f0f7ff; border-radius: 6px;">
                        <div style="font-size: 18px; font-weight: bold; color: #1890ff;" id="transferSpeed">0 KB/s</div>
                        <div style="font-size: 12px; color: #666;">传输速率</div>
                    </div>
                    <div style="text-align: center; padding: 10px; background: #f6ffed; border-radius: 6px;">
                        <div style="font-size: 18px; font-weight: bold; color: #52c41a;" id="transferredSize">0 MB</div>
                        <div style="font-size: 12px; color: #666;">已传输</div>
                    </div>
                    <div style="text-align: center; padding: 10px; background: #fff7e6; border-radius: 6px;">
                        <div style="font-size: 18px; font-weight: bold; color: #fa8c16;" id="remainingTime">计算中</div>
                        <div style="font-size: 12px; color: #666;">剩余时间</div>
                    </div>
                </div>
                
                <!-- 操作按钮 -->
                <div style="text-align: center;">
                    <button type="button" class="layui-btn layui-btn-danger" id="cancelTransferBtn">
                        <i class="layui-icon layui-icon-pause"></i>
                        取消传输
                    </button>
                    <button type="button" class="layui-btn layui-btn-primary" id="closeProgressBtn">
                        <i class="layui-icon layui-icon-close"></i>
                        关闭窗口
                    </button>
                </div>
            </div>
        `;
        
        const progressIndex = this.layer.open({
            type: 1,
            title: [
                '<i class="layui-icon layui-icon-chart" style="margin-right: 10px;"></i>传输进度监控',
                'font-size: 16px;'
            ],
            area: ['480px', 'auto'],
            maxmin: true,
            closeBtn: 0,
            content: progressHTML,
            success: (layero, index) => {
                this.setupProgressEvents(layero, index);
            }
        });
        
        return progressIndex;
    }


    /**
    * 设置传输进度弹窗事件
    * @param {jQuery} layero 弹层jQuery对象
    * @param {number} layerIndex 弹层索引
    */
    setupProgressEvents(layero, layerIndex) {
        // 取消传输按钮事件
        layero.find('#cancelTransferBtn').on('click', () => {
            this.layer.confirm(
                '确定要取消当前传输任务吗？<br><small style="color: #999;">取消后需要重新开始传输</small>',
                {
                    icon: 3,
                    title: '确认取消',
                    area: ['320px', 'auto']
                },
                (confirmIndex) => {
                    this.cancelTransfer();
                    this.layer.close(confirmIndex);
                    this.layer.close(layerIndex);
                }
            );
        });
        
        // 关闭窗口按钮事件
        layero.find('#closeProgressBtn').on('click', () => {
            this.layer.close(layerIndex);
            // 发送停止发送进度事件
            window.SocketClient.emit('stop_progress', {});
        });
    }

    /**
    * 取消传输
    */
    cancelTransfer() {
        console.log('取消传输任务');
        
        // 重置传输状态
        this.isTransferring = false;
        this.currentTransfer = {
            fileName: '',
            totalSize: 0,
            transferredSize: 0,
            speed: 0,
            remainingTime: 0,
            progress: 0,
            startTime: null,
            progressTimer: null
        };
        
        this.layer.msg('传输已取消', {icon: 2});
        
        // 这里可以添加实际的取消传输API调用
        // 例如：调用后端API取消传输任务
        /*
        fetch('/api/cancel-transfer', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({taskId: this.currentTransfer.taskId})
        }).then(response => {
            console.log('传输取消请求已发送');
        });
        */
       window.SocketClient.socket.emit('stop_transfer', {});

    }

    
    /**
     * 处理下载请求
     * @param {Object} formData 表单数据
     * @param {number} layerIndex 弹层索引
     */
    handleDownload(formData, layerIndex) {
        console.log('开始处理下载请求...', formData);
        
        // 更新配置
        Object.assign(this.config, formData);
        
        // 执行下载前回调
        if (this.callbacks.onDownloadStart) {
            this.callbacks.onDownloadStart(this.config);
        }
        
        // 显示确认对话框
        this.layer.confirm(
            `确定要下载文件吗？<br><br>
            <strong>传输模式:</strong> ${formData.transferMode === 'scp' ? 'SCP直传' : '服务器中转'}<br>
            <strong>远程地址:</strong> ${formData.srcIp}:${formData.srcPath}<br>
            <strong>本地路径:</strong> ${formData.destPath}`,
            {
                icon: 3,
                title: '确认下载',
                area: ['400px', 'auto']
            },
            (confirmIndex) => {
                this.layer.close(confirmIndex);
                this.layer.close(layerIndex);
                this.performDownload(this.config);
            }
        );
    }

    handleStopTransfer(formData, layerIndex) {
        console.log('开始处理停止传输请求...', formData);
        window.SocketClient.socket.emit('stop_transfer', {});
    }

    
    /**
     * 执行实际下载
     * @param {Object} config 下载配置
     */
    performDownload(config) {
        console.log('开始执行下载...', config);
        
        // 显示进度条
        // const progressIndex = this.showProgressDialog();
        
        console.log('开始执行下载...', config);

        // 生成哈希值
        config.event = 'download';
        // config.id = config.event+'-'+config.srcIp +'-'+ config.srcUsername +'-'+ config.srcPath +'-'+config.destIp +'-'+config.destUsername+ config.destPath;
        config.time = Date.now().toString();
        


        window.SocketClient.socket.emit('download_file', config);

        
        // 模拟点击
        // setTimeout(() => {
            
        // }, 1000);
        document.getElementById('showProgressBtn').click();


        // 模拟下载过程
        // this.simulateDownload(config, progressIndex);
    }
    
    /**
     * 显示下载进度对话框
     * @returns {number} 弹层索引
     */
    showProgressDialog() {
        const progressHTML = `
            <div style="padding: 30px;">
                <div style="text-align: center; margin-bottom: 20px;">
                    <i class="layui-icon layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop" 
                       style="font-size: 32px; color: #1890ff;"></i>
                </div>
                <div style="margin-bottom: 15px;">
                    <div class="layui-progress" lay-filter="downloadProgress">
                        <div class="layui-progress-bar layui-bg-blue" lay-percent="0%"></div>
                    </div>
                </div>
                <div style="text-align: center;">
                    <span id="progressText">准备下载...</span>
                </div>
                <div style="text-align: center; margin-top: 20px;">
                    <button type="button" class="layui-btn layui-btn-sm layui-btn-danger" id="cancelDownloadProgress">
                        取消下载
                    </button>
                </div>
            </div>
        `;
        
        return this.layer.open({
            type: 1,
            title: '下载进度',
            area: ['400px', 'auto'],
            closeBtn: 0,
            content: progressHTML
        });
    }
    
    /**
    * 模拟下载过程
    * @param {Object} config 下载配置
    * @param {number} progressIndex 进度弹层索引
    */
    simulateDownload(config, progressIndex) {
        // 设置传输状态
        this.isTransferring = true;
        this.currentTransfer = {
            fileName: config.srcPath.split('/').pop() || 'unknown_file',
            totalSize: 50 * 1024 * 1024, // 模拟50MB文件
            transferredSize:1*1024*1024,
            speed: 10*1024*1024,
            remainingTime: 5,
            progress: 0,
            startTime: null,
            progressTimer: null
        };
        
        let progress = 0;
        let speed = 0; // KB/s
        const progressElement = this.element;
        
        const timer = setInterval(() => {
            // 模拟传输进度
            const increment = Math.random() * 8 + 2; // 2-10%
            progress += increment;
            
            // 计算传输大小和速度
            this.currentTransfer.transferredSize = (progress / 100) * this.currentTransfer.totalSize;
            const elapsedSeconds = (new Date() - this.currentTransfer.startTime) / 1000;
            speed = this.currentTransfer.transferredSize / 1024 / elapsedSeconds; // KB/s
            
            if (progress >= 100) {
                progress = 100;
                clearInterval(timer);
                this.isTransferring = false;
                
                // 下载完成
                setTimeout(() => {
                    this.layer.close(progressIndex);
                    this.onDownloadComplete(config);
                }, 500);
            }
            
            // 更新进度条
            progressElement.progress('downloadProgress', progress + '%');
            progressElement.progress('transferProgress', progress + '%');
            
            // 更新进度文字
            const progressText = progress < 100 ? 
                `正在下载... ${Math.round(progress)}%` : 
                '下载完成!';
            $('#progressText').text(progressText);
            
            // 更新传输监控窗口数据
            this.updateProgressDisplay(progress, speed);
            
            // 回调进度更新
            if (this.callbacks.onDownloadProgress) {
                this.callbacks.onDownloadProgress(progress, config);
            }
            
        }, 300);
        
        this.currentTransfer.progressTimer = timer;
        
        // 取消下载按钮事件
        $('#cancelDownloadProgress').on('click', () => {
            this.cancelTransfer();
            this.layer.close(progressIndex);
        });
    }


    /**
    * 更新传输进度显示
    * @param {number} progress 进度百分比
    * @param {number} speed 传输速度(KB/s)
    */
    updateProgressDisplay(progress_num,progress, speed, remainingTime,transferredSize,totalSize) {

        // 更新进度条
        // document.getElementById('downloadProgress').setAttribute('lay-percent', progress_num);
        // document.getElementById('transferProgress').setAttribute('lay-percent', progress_num);
        this.element.progress('downloadProgress', progress_num + '%');
        this.element.progress('transferProgress', progress_num + '%');


        // 更新进度百分比
        document.getElementById('progressPercent').textContent = progress;


        // 更新传输速度
        document.getElementById('transferSpeed').textContent = speed;
        
        // 更新已传输大小
        document.getElementById('transferredSize').textContent = transferredSize+'/'+totalSize;
        
        // 更新剩余时间
        document.getElementById('remainingTime').textContent = remainingTime;
    }

    
    /**
     * 下载完成处理
     * @param {Object} config 下载配置
     */
    onDownloadComplete(config) {
        console.log('下载完成:', config);
        
        this.layer.alert(
            `文件下载完成！<br><br>
            <strong>文件路径:</strong> ${config.destPath}<br>
            <strong>传输模式:</strong> ${config.transferMode === 'scp' ? 'SCP直传' : '服务器中转'}`,
            {
                icon: 1,
                title: '下载完成',
                area: ['400px', 'auto']
            }
        );
        
        // 执行完成回调
        if (this.callbacks.onDownloadComplete) {
            this.callbacks.onDownloadComplete(config);
        }
    }
    
    /**
     * 更新配置
     * @param {Object} newConfig 新配置
     */
    updateConfig(newConfig) {
        Object.assign(this.config, newConfig);
        console.log('配置已更新:', this.config);
    }
    
    /**
     * 获取当前配置
     * @returns {Object} 当前配置的副本
     */
    getConfig() {
        return { ...this.config };
    }
    
    /**
     * 重置配置到默认值
     */
    resetConfig() {
        this.config = {
            time: '',
            event: '',
            srcIp: '',
            srcPath: '',
            srcUsername: '',
            srcPassword: '',
            destIp: '',
            destPath: '',
            destUsername: '',
            destPassword: '',
            transferMode: 'scp', // scp 或 server
        };
        console.log('配置已重置');
    }
    
    /**
     * 设置回调函数
     * @param {Object} callbacks 回调函数对象
     */
    setCallbacks(callbacks) {
        Object.assign(this.callbacks, callbacks);
    }


    /**
     * 获取本地IP地址（模拟）
     * 实际项目中可能需要通过API获取
     */
    getdestIp() {
        // 这里是模拟的本地IP获取
        // 实际项目中可以通过WebRTC或服务器API获取
        return '192.168.1.10';
    }

}

window.FileDownloadManager = new FileDownloadManager();